import { warn, error as printError } from "@/utils/log";
/* eslint-disable no-case-declarations */
/* eslint-disable no-debugger */
import { useState, useEffect, useCallback, useRef } from "react";
import useToken from "./useToken";
import { notification } from "antd";
let socketUrl: any = import.meta.env.VITE_GLOB_WEBSOCKET_URL; //URL地址
let heartTime: any = null; // 心跳定时器实例
let socketHeart = 0 as number; // 心跳次数
const HeartTimeOut = 10000; // 心跳超时时间 10000 = 10s
let socketError = 0 as number; // 错误次数
let closeFlag = false;
const UseWebSocket = () => {
	const { token } = useToken();
	const [reset, setReset] = useState(false);
	const [message, setMessage] = useState<any>();
	const socket = useRef<WebSocket | null>(null);
	const socketOnClose = useCallback((e: CloseEvent) => {
		// 处理关闭事件
		// console.log("断开连接", e);
		socketError = 0;
		warn("SOCKET连接断开 ");
	}, []);

	const socketOnError = useCallback((error: Event) => {
		// 处理错误事件
		// console.log("连接 websocket 失败", error);
		printError("SOCKET连接失败");
	}, []);

	const socketOnMessage = useCallback((event: MessageEvent) => {
		// 处理消息事件
		// console.log("Received message:", event.data);
		if (event.data.indexOf("heartbeat") > 0) {
			resetHeart();
		}
		if (event.data.indexOf("ping") > 0) {
			return;
		}
		const data = JSON.parse(event.data);
		switch (data?.type) {
			case "notice":
				const messageObj = JSON.parse(data?.data);
				notification.success({ placement: "bottomRight", message: messageObj.title, description: messageObj.desc, duration: 2 });
				const u = new SpeechSynthesisUtterance();
				u.text = messageObj.desc;
				u.lang = "zh";
				u.rate = 0.7;
				speechSynthesis.speak(u);
				break;
		}
		setMessage(event.data);
	}, []);

	const socketOnOpen = useCallback(() => {
		// 处理连接打开事件
		console.log("SOCKET连接成功");
		resetHeart();
	}, []);

	const socketInit = useCallback(() => {
		try {
			// eslint-disable-next-line no-debugger
			// debugger;
			// if (socket.current != null) return;
			if (import.meta.env.VITE_APP_WEBSOCKET === "false") return;
			if (!token) return;
			const url = socketUrl + "?Authorization=Bearer " + token + "&clientid=" + import.meta.env.VITE_GLOB_CLIENT_ID;
			const socketObj = new WebSocket(url);
			socketObj.addEventListener("close", socketOnClose);
			socketObj.addEventListener("error", socketOnError);
			socketObj.addEventListener("message", socketOnMessage);
			socketObj.addEventListener("open", socketOnOpen);
			// setSocket(socketObj);
			socket.current = socketObj;
		} catch (e) {
			console.log(e);
		}
	}, [socketOnClose, socketOnError, socketOnMessage, socketOnOpen, token]);

	useEffect(() => {
		socketInit();
		return () => {
			if (socket) {
				socket.current?.close();
			}
		};
	}, [socketInit]);

	useEffect(() => {
		if (!reset) return;
		const timer = setTimeout(() => {
			socketInit();
			setReset(false);
		}, 30000);
		return () => clearTimeout(timer);
	}, [reset, socketInit]);
	// socket 重置心跳
	const resetHeart = () => {
		socketHeart = 0;
		socketError = 0;
		clearInterval(heartTime);
		sendSocketHeart();
	};
	//发送心跳
	const sendSocketHeart = () => {
		heartTime = setInterval(() => {
			// 如果连接正常则发送心跳
			if (socket.current?.readyState === 1) {
				socket.current?.send(
					JSON.stringify({
						type: "ping"
					})
				);
				socketHeart = socketHeart + 1;
			} else {
				// 重连
				reconnect();
			}
		}, HeartTimeOut);
	};
	// socket重连
	const reconnect = () => {
		if (socketError <= 2) {
			clearInterval(heartTime);
			// initWebSocket(socketUrl);
			socketInit();
			socketError = socketError + 1;
			console.log("socket重连", socketError);
		} else {
			console.log("重试次数已用完");
			clearInterval(heartTime);
		}
	};
	//发送消息
	const sendMessage = (data: any) => {
		if (socket.current) {
			socket.current.send(JSON.stringify(data));
		}
	};
	const close = () => {
		// closeFlag = true;
		// socket.current?.onclose(socket.current);
		socket.current?.close();
	};
	return { socket, setReset, message, sendMessage, close };
};

export default UseWebSocket;
